package com.ck567.netty.chatroom.server.handler

import com.ck567.netty.chatroom.message.GroupCreateRequestMessage
import com.ck567.netty.chatroom.message.GroupCreateResponseMessage
import com.ck567.netty.chatroom.server.session.GroupSessionFactory
import com.ck567.netty.chatroom.util.logger
import io.netty.channel.ChannelHandler
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.SimpleChannelInboundHandler

@ChannelHandler.Sharable
class GroupCreateMessageHandler : SimpleChannelInboundHandler<GroupCreateRequestMessage>() {

    override fun channelRead0(ctx: ChannelHandlerContext, msg: GroupCreateRequestMessage) {
        logger.info("==================")
        logger.info("创建群组：$msg")
        val group = GroupSessionFactory.getSession().createGroup(msg.name, msg.members)
        if (group == null) {
            ctx.writeAndFlush(GroupCreateResponseMessage(true, "您成功创建群聊-${msg.name}"))
            val channelList = GroupSessionFactory.getSession().getMembersChannel(msg.name)
            channelList?.forEach { channel ->
                if(channel != ctx.channel()){
                    channel?.writeAndFlush(GroupCreateResponseMessage(true, "您已被拉入群聊-${msg.name}"))
                }
            }
            logger.info("创建成功！")
        } else {
            ctx.writeAndFlush(GroupCreateResponseMessage(false, "创建群聊失败，该群聊已存在"))
            logger.info("创建失败！")
        }
    }

    companion object {
        private val logger = logger<GroupCreateMessageHandler>()
    }
}